package com.rsscollector.controller.taglibs.app;

import com.rsscollector.model.vo.Category;
import com.rsscollector.model.vo.RssSource;
import com.rsscollector.model.CatalogFacade;

import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;
import java.io.Writer;


public class CatalogTreeTag extends SimpleTagSupport {
    @Override
    public void doTag() throws JspException, IOException {
        JspWriter writer = this.getJspContext().getOut();
        try {
            for (Object obj : CatalogFacade.getRootCategories(true)) {
                Category category = (Category) obj;
                printCategoryNode(category, writer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printCategoryNode(Category category, Writer w) throws Exception {
        w.write("<div dojoType=\"TreeNode\" title=\"" + category.getName() + "\" widgetId=\"cat" + category.getId() + "\" isFolder=\"true\">");
        if (category.getSubCategories().size() > 0) {
            w.write("\n");
            for (Category sub : category.getSubCategories()) {
                printCategoryNode(sub, w);
                w.write("\n");
            }
        }
        if (category.getRssSources().size() > 0) {
            w.write("\n");
            for (RssSource s : category.getRssSources()) {
                printSourceNode(s, w);
                w.write("\n");
            }
        }
        w.write("</div>");
    }

    private static void printSourceNode(RssSource s, Writer w) throws IOException {
        w.write("<div dojoType=\"TreeNode\" title=\"" + s.getRssUrl() + "\" widgetId=\"url" + s.getId() + "\" isFolder=\"false\"></div>");
    }
}
